<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Repositories\UserLogRepository;
use App\Repositories\UserRepository;
use App\Http\Requests\Admin\User\ShowRequest;
use App\Http\Requests\Admin\User\QueryResource;
use App\Http\Requests\Admin\User\UserCreate;
use App\Http\Requests\Admin\User\UserUpdate;
use App\Http\Requests\Admin\User\UserDestroy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    protected $userRepository;
    protected $userLogRepository;

    /**
     * UserController constructor.
     * @param UserRepository $userRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        UserRepository $userRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->userRepository = $userRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取用户资源列表
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $limit = $request->get('paginate', 15);
        $server_id = $request->get('server_id', false);
        $name = $request->get('name', false);
        $created_at = $request->get('created_at', false);
        if ($server_id === null) {
            $server_id = false;
        }
        if ($name === null) {
            $name = false;
        }
        if ($created_at === null) {
            $created_at = false;
        }
        $users = $this->userRepository->getUsers($server_id, $name, $created_at, $limit);
        return success($users);
    }

    /**
     * 根据用户Id 获取用户详情资源
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param ShowRequest $request
     * @param $user
     * @return \Illuminate\Http\JsonResponse
     * @throws GeneralException
     */
    public function show(ShowRequest $request, $user)
    {
        $limit = $request->get('paginate', 15);
        if (!is_numeric($user)) {
            return failed('请上传正确的用户id', 422);
        }
        $res = $this->userRepository->getUsersDetails($user, $limit);
        return success($res);
    }

    /**
     * 新建用户资源
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param UserCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(UserCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        $users = $this->userRepository->create($attributes);
        //记录日志
        $admins = Auth::guard('admin')->user();
        $uid = $admins->id;
        $service_id = 0;
        $name = $admins->name;
        $operation = '创建了会员[' . $users->phone . ']';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored($users);
    }

    /**
     * 更新用户信息
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param UserUpdate $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function update(UserUpdate $request, User $user)
    {
        $usersAttr = array_filter($request->only([
            'name',
            'phone',
        ]), function ($value) {
            if ($value === null || $value === '') {
                return false;
            } else {
                return true;
            }
        });
        $userArray = [
            'name' => $user->name,
            'phone' => $user->phone,
        ];
        if ($userArray == $usersAttr) {
            //return failed('没有可更新内容', 422);
            $uid_info = $this->userRepository->getUsersInfo($user->id);
            return updated($uid_info, '没有可更新内容');
        }
        $user->update($usersAttr);
        //根据服务站id获取服务站名称
        $user->service_name = '';
        $service_id = $user->service_id;
        if ($service_id) {
            $service = DB::table('service')
                ->select('designation as service_name')
                ->where('id', '=', $service_id)->first();
            if ($service && $service->service_name) {
                $user->service_name = $service->service_name;
            }
        }
        if ($userArray['name'] === $usersAttr['name']) {
            unset($userArray['name'], $usersAttr['name']);
        }
        if ($userArray['phone'] === $usersAttr['phone']) {
            unset($userArray['phone'], $usersAttr['phone']);
        }
        //记录日志
        $admins = Auth::guard('admin')->user();
        $uid = $admins->id;
        $service_id = 0;
        $name = $admins->name;
        $operation = '更新了会员[' . $user->phone . ']资料';
        $history = json_encode($userArray, true);
        $actuality = json_encode($usersAttr, true);
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        $uid_info = $this->userRepository->getUsersInfo($user->id);
        return updated($uid_info);
    }

    /**
     * 删除 用户 资源
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param UserDestroy $request
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function destroy(UserDestroy $request, User $user)
    {
        $user->delete();
        //记录日志
        $admins = Auth::guard('admin')->user();
        $uid = $admins->id;
        $service_id = 0;
        $name = $admins->name;
        $operation = '删除了会员[' . $user->phone . ']';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 检测手机号码是否存在
     *
     * Date: 2018/06/10
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function existence(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/', 'unique:user,phone']
        ], [
            'phone.required' => '请输入手机号码',
            'phone.regex' => '您输入的手机号码有误',
            'phone.unique' => '您输入的手机号码已存在'
        ]);
        return message('可以注册');
    }
}
